#include "widget.h"
#include "ui_widget.h"
#include<QMessageBox>
#include<QNetworkDatagram>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //创建出示例
    socket = new QUdpSocket(this);


    //设置窗口标题
    this->setWindowTitle("服务器");

    //连接信号槽
    connect(socket,&QUdpSocket::readyRead,this,&Widget::processRequest);

    //绑定端口号
    bool ret = socket->bind(QHostAddress::Any,9090);
    if(!ret)
    {
        //绑定失败
        QMessageBox::critical(this,"服务器启动出错",socket->errorString());
        return;
    }
}

Widget::~Widget()
{

    delete ui;
}


//就是服务器的最核心逻辑
void Widget::processRequest()
{
    //读取请求并解析
    const QNetworkDatagram& requstDatagram = socket->receiveDatagram();
    QString request = requstDatagram.data();
    //根据请求计算相应(回显服务器，响应就是请求本省)
    const QString &response = process(request);

    //把响应写给客户端
    QNetworkDatagram responseDatagram(response.toUtf8(),requstDatagram.senderAddress());
    socket->writeDatagram(responseDatagram);
    //取出QSting的字节数组response.toUtf8()

    //把交互的信息显示到界面上
    QString log = "["+requstDatagram.senderAddress().toString()+ ":"+QString::number(requstDatagram.senderPort())
            + "]req:" +request + ",resp:" +response;

    ui->listWidget->addItem(log);
}

QString Widget::process(const QString &request)
{
    //由于是回显服务器  响应和请求是完全一样的
    //
    return request;
}

